package com.hksj.wmp.auth;

import com.hksj.common.core.common.ClientType;
import com.hksj.common.core.exception.ApplicationException;
import com.hksj.common.core.util.RSAUtils;
import com.hksj.jetlinks.entity.User;
import com.hksj.jetlinks.model.LoginUser;
import com.hksj.jetlinks.service.JetUserService;
import com.hksj.wmp.service.WxLoginService;
import com.hksj.wmp.vo.MenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class WxAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private JetUserService jetUserService;
    @Autowired
    private WxLoginService wxLoginService;
    @Autowired
    private WxPasswordEncoder wxPasswordEncoder;
    @Value("${hk.rsa.private}")
    private String privateSecurity;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WxUsernamePasswordAuthenticationToken wxUserNamePasswordAuthenticationToken = (WxUsernamePasswordAuthenticationToken) authentication;
        User user = jetUserService.lambdaQuery()
                .eq(User::getUsername, wxUserNamePasswordAuthenticationToken.getName())
                .one();
        if (ObjectUtils.isEmpty(user)){
            throw new ApplicationException(wxUserNamePasswordAuthenticationToken.getName() + "账号不存在");
        }
        if (!Objects.equals(user.getStatus(), 1)){
            throw new ApplicationException(wxUserNamePasswordAuthenticationToken.getName() + "已被禁用");
        }

        String plainPassword = RSAUtils.decrypt(wxUserNamePasswordAuthenticationToken.getPassword(), privateSecurity);
        if (!Objects.equals(wxPasswordEncoder.encode(plainPassword, user.getSalt()),user.getPassword())){
            throw new ApplicationException("账号密码错误");
        }

        List<MenuVO> menus = wxLoginService.listMenuByUserId(user.getId());
        List<String> menuCodeList = menus.stream().map(menu -> menu.getCode()).collect(Collectors.toList());
        user.setPassword(null);
        user.setSalt(null);
        LoginUser loginUser = new LoginUser(user, menuCodeList, null, ClientType.MINI_PROGRAM.value());
        return new WxUsernamePasswordAuthenticationToken(loginUser);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (WxUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
